<?php

class Tag_model extends CI_Model {

	public $content;

	public function getTag($tagId)	{
		$this->db->where('id', $tagId);
		$result = $this->db->get('tags', 1)->result();
		if (count($result) > 0)
			return $result[0];
		return null;
	}
	
	public function getPopularTags()	{
		$this->db->select('tags.id as tid, tagId, content, count(productId) as total');
		$this->db->join('producttags', 'producttags.tagId = tags.id', 'left');
		$this->db->group_by('tid');
		$this->db->order_by('total DESC');
		return $this->db->get('tags', 15)->result();
	}
	
	public function getTagByContent($tag) {
		$this->db->where('content', $tag);
		$result = $this->db->get('tags', 1)->result();
		if (count($result) > 0)	{
			return $result[0]->id;
		}
		$this->content = $tag;
		$result = $this->db->insert('tags', $this);
		if ($result)	{
			return $this->db->insert_id();
		}
		return false;
	}
	
	public function tagProduct($productId, $tagId)	{
		return $this->db->insert('producttags', array('productId'=>$productId, 'tagId'=>$tagId));
	}
}

?>